import { defineStore } from "pinia"
import router from "@/router"
import { ElMessage as message } from "element-plus"
import { useAuthStore, useNavTagsStore, useDictionaryStore } from "@/store"
import { authRouteMode } from "@/common/config"
import { resetRouter } from "@/router"
import { setToken, deleteToken } from "@/common/utils"
import { logoutApi } from "@/api/user"
import { getDictionaryListApi, getSuccessStatus } from "@/api/dictionary"



export default defineStore('user', {
  state: () => ({
    info: {} as UserType,            // 用户信息
    loginInfo: {} as LoginFormInfoType,   // 登录表单信息
  }),
  actions: {
    setUser(user: UserType) {
      this.info = user
    },
    async login(token: string) {
      setToken(token)
      try { await this.initDictionaries() } catch (error) { console.log("初始化全局字典时出错", error) }
    },
    /**初始化常用的全局字典 */
    async initDictionaries() {
      const dictionaryNames: string[] = []
      const dictionaries: ObjType = {}
      for (const v of dictionaryNames) {
        const res = await getDictionaryListApi({ categoryName: v })
        if (res.code == getSuccessStatus()) dictionaries[v] = res.data
      }
      const dictionaryStore = useDictionaryStore()
      dictionaryStore.setData(dictionaries)
    },
    async logout(redirect: string, sendReq = true) {
      const execute = () => {
        deleteToken()
        this.info = {} as UserType
        const authStore = useAuthStore()
        const navTagsStore = useNavTagsStore()
        router.replace({ path: "/login", query: { redirect: encodeURIComponent(redirect) } })
        setTimeout(()=>{navTagsStore.clearTags(true)},100)
        if (authRouteMode !== "local") {
          authStore.clearRoutes()
          resetRouter()
        }
      }

      if (sendReq) {
        const res = await logoutApi()
        if (res.code == getSuccessStatus() && res.data) execute()
        else message.error("退出登录失败")
      } else execute()
    }
  },


})